// pages/order/order.js
var util = require('../../utils/util.js') ;
const GetPeriod = require("../../utils/getperiod.js");
const app = getApp();
Page({
  
  /**
   * 页面的初始数据
   */
  data: {
    'getAddress': '',
    'finalAddress': '',
    'kehuPhone': '',
    'orderStatus':'',
   
     displaySta: 'none',
     changeS:'dayshang',
     changeX:'dayxia',
     orderInfo:{},
     orderTime:{},
     dateType: 0,
     dateTypeR: 'now',
     startDate: '',
     endDate: '',


     peisongIng: '',
     peisongCompleted: '',
     waitRenling: '',
     ids:'',
     counter:'',
    totalAmount:'',
     bgcolor:'',
  },
  
  // 时间段选择  
  
  zhankai:function(){
    if(this.data.displaySta == 'none'){
      this.setData({
        displaySta: 'block'
      })
      }else{
        this.setData({
          displaySta: 'none'
        })
      }
    },
  detail:function(e){
    console.log(e.currentTarget.dataset.id)
    getApp().globalData.orderId = e.currentTarget.dataset.id
  },
  detailPage:function(){
    wx.navigateTo({
      url: '../detail/detail',
    })
  },
  peisong:function(e){
    var token = app.globalData.token
    console.log("our Order id is:" + e.currentTarget.dataset.id)
    console.log("our token is:" + token)
    var status = app.globalData.peisongIng
    wx.request({
      url: 'https://www.cycs023.cn/f50m-web/api/orders/' + e.currentTarget.dataset.id +'/',
    data:{
      status : status
    },
    method:'PUT',
    header: {
        'content-type': 'application/json',
        'X-SDX-Token': token
      },
    success:function(res){
      if(res.statusCode == 200){
        wx.showToast({
          title: '配送完成',
          icon: 'success',
          duration: 1000
        })
      }
    },
    fail:function(res){
      wx.showModal({
        title: '配送完成失败',
        content: '请重新操作',
      })
    }
    })
  
  },
  refresh:function(){
    var point = this
    this.getOrder(this.data.startDate,this.data.endDate,point);
  },

  getOrder:function(start_date,end_date,point){
    var token = app.globalData.token
    var that = this
    var ids = new Array()
    console.log("our token is:" + token)
    wx.showLoading({
      title: '加载中....',
    })
    wx.request({
      url: 'https://www.cycs023.cn/f50m-web/api/orders?',
      data: {
        createStartTime: start_date + " 00:00:00",
        createEndTime: end_date + " 23:59:59",
        status: app.globalData.peisongCompleted
      },
      method: 'GET',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'X-SDX-Token': token
      },
      success: function (res) {
        if (res.statusCode == 200) {
          console.log("获取到的为：" + res)
          point.setData({
            orderInfo: res.data.data.rows,
            counter : res.data.data.total,
          })
          wx.request({
            url: 'https://www.cycs023.cn/f50m-web/api/orders/statistics/' + app.globalData.peisongCompleted,
            data: {
              createStartTime: point.data.startDate + " 00:00:00",
              createEndTime: point.data.endDate + " 23:59:59",
              flag: 0,
            },
            method: 'GET',
            header: {
              'content-type': 'application/x-www-form-urlencoded',
              'X-SDX-Token': token
            },
            success: function (res) {
              if (res.statusCode == 200) {
                 point.setData({
                   counter:res.data.data.rows[0].orderNum,
                   totalAmount: res.data.data.rows[0].totalAmount
                 })
                 console.log(point.data.totalAmount)
              }
            }
          })
          var newTime = new Array()
          var newDate = new Array()
          for (var i = 0; i < res.data.data.rows.length; i++) {
            newDate = res.data.data.rows[i].updateTime
            let time = 'orderInfo[' + i + '].receiptTime'
            that.setData({
              [time]: res.data.data.rows[i].receiptTime.substring(11,16)
            })
            let date = 'orderInfo[' + i + '].apartmentId'
            that.setData({
              [date]: newDate.substring(5, 10)
            })
          }
          console.log(point.data.orderInfo)
          wx.hideLoading();
        } else if (res.statusCode == 401) {
          wx.hideLoading();
          
        }
      }
    })
  },
 
  getDateTypeR(e) {
    let dateType = e.currentTarget.dataset.datetype;
    this.setData({
      dateTypeR: dateType,
      date: this.time.getPeriod({ periodType: dateType })
    })
  },
  // 获取当前时间段
  getDateType(e) {
    let dateType = e.currentTarget.dataset.datetype;
    let startDate = '', endDate = '';
    var point = this;
    if (dateType == 0) {//今天
      startDate = this.time.getNowDate();
      endDate = this.time.getNowDate();
      this.getOrder(startDate, endDate, point)
      this.zhankai()
      console.log(startDate + "~" + endDate)
    } else if (dateType == 1) {//本周
      startDate = this.time.getWeekStartDate();
      endDate = this.time.getWeekEndDate();
      this.getOrder(startDate, endDate, point)
      this.zhankai()
      console.log(startDate + "~" + endDate)
    } else if (dateType == 2) {//本月
      startDate = this.time.getMonthStartDate();
      endDate = this.time.getMonthEndDate();
      this.getOrder(startDate, endDate, point)
      this.zhankai()
      console.log(startDate + "~" + endDate)
    } else if (dateType == 3) {//本年
      startDate = this.time.getYearStartDate();
      endDate = this.time.getYearEndDate();
      this.getOrder(startDate, endDate, point)
      this.zhankai()
      console.log(startDate + "~" + endDate)
    } else if (dateType == 4) {//选择时段初始化为当天时间段
      startDate = this.time.getNowDate();
      endDate = this.time.getNowDate();
      this.getOrder(startDate, endDate, point)
      this.zhankai()
      console.log(startDate + "~" + endDate)
    } else if (dateType == 5) {//本季度
      startDate = this.time.getQuarterStartDate();
      endDate = this.time.getQuarterEndDate();
      this.getOrder(startDate, endDate, point)
      this.zhankai()
      console.log(startDate + "~" + endDate)
    }
    this.setData({ dateType: dateType, startDate: startDate, endDate: endDate });
  },
  bindDateChange(e) {
    var point = this
    if (e.currentTarget.id == 'start') {
      this.setData({ startDate: e.detail.value })
      this.getOrder(this.data.startDate, this.data.endDate, point)
    } else if (e.currentTarget.id == 'end') {
      this.setData({ endDate: e.detail.value })
      this.getOrder(this.data.startDate, this.data.endDate, point)
    } else {
      return;
    }
  },
  
  
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.time = new GetPeriod();
    this.setData({ dateType: 0, startDate: this.time.getNowDate(), endDate: this.time.getNowDate() });
    console.log(this.data.startDate)
    var point=this
    if(app.globalData.confirmSta){
      point.getOrder(point.data.startDate, point.data.endDate,point)
    }else{
      point.setData({
        counter : 0,
        totalAmount:0,
      })
      wx.showModal({
        title: '提示',
        content: '请前往个人中心验证账号',
        success: function (res) {
          if (res.confirm) {
            console.log('弹框后点取消')
            wx.switchTab({
              url: '../person/person',
            })
          } else {
            console.log('弹框后点取消')
          }
        }
      })
    }
    this.setData({
      peisongIng: app.globalData.peisongIng,
      peisongCompleted: app.globalData.peisongCompleted,
      waitRenling: app.globalData.waitRenling,
    })
  },
  phoneCall: function (e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.replyPhone,
      success: function () {
        console.log("成功拨打电话")
      },
    })
  },
  testSubmit: function (e) {
    var token = app.globalData.token
    let formId = e.detail.formId;
    this.dealFormIds(formId); //处理保存推送码
    console.log(formId)
    let type = e.detail.target.dataset.type;
    //根据type的值来执行相应的点击事件
    wx.request({
      url: 'https://www.cycs023.cn/f50m-web/api/formids/',
      data: {
        formId: formId
      },
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'X-SDX-Token': token
      },
      success: function (res) {
        if (res.statusCode == 200) {
           console.log('success')
        }
      }
    })
  },
  dealFormIds: function (formId) {
    let formIds = app.globalData.gloabalFomIds;//获取全局数据中的推送码gloabalFomIds数组
    if (!formIds) formIds = [];
    let data = {
      formId: formId,
      expire: parseInt(new Date().getTime() / 1000) + 604800 //计算7天后的过期时间时间戳
    }
    formIds.push(data);//将data添加到数组的末尾
    app.globalData.gloabalFomIds = formIds; //保存推送码并赋值给全局变量
  },
  allComp:function(){
    var token = app.globalData.token
    console.log("our token is:" + token)
    var status = app.globalData.peisongIng
    var that = this
    wx.request({
      url: 'https://www.cycs023.cn/f50m-web/api/orders/',
      data: {
        status: status,
        ids: that.data.ids
      },
      method: 'PUT',
      header: {
        'content-type': 'application/json',
        'X-SDX-Token': token
      },
      success: function (res) {
        if (res.statusCode == 200) {
          wx.showToast({
            title: '配送成功',
            icon: 'success',
            duration: 1000
          })
        }
      }
    })
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },
  
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})